package com.heima.comment.Interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

public class MvcHandleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.从请求头获得token
        String token = request.getHeader("token");
        Optional<String> optional = Optional.ofNullable(token);
        if (optional.isPresent()) {
            //2.解析token,获取用户id
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims != null) {
                Integer userid = (Integer) claims.get("id");
                //3.存入threadLocal中
                ApUser apUser = new ApUser();
                apUser.setId(userid);
                ApThreadLocalUtil.setUser(apUser);
            }
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApThreadLocalUtil.clear();
    }
}
